<?php

namespace App\Admin\Grid\Displayers;

use Illuminate\Contracts\Support\Arrayable;

class Image extends AbstractDisplayer
{
    public function display($server = '', $width = 30, $height = 30)
    {
        if (is_string($this->value)) {
            $this->value = explode(',', $this->value);
        }

        // 单文件带管理的情况
        if (is_array($this->value) && isset($this->value['path'])) {
            $this->value = [$this->value];
        }

        if ($this->value instanceof Arrayable) {
            $this->value = $this->value->toArray();
        }

        return collect((array)$this->value)->filter()->map(function ($path) use ($server, $width, $height) {
            // 处理使用了文件管理的情况
            if (is_array($path) && isset($path['path'])) {
                $path = $path['path'];
            }

            if (url()->isValidUrl($path)) {
                $src = $path;
            } else {
                $server = $server ?: config('admin.upload.host');
                $src = trim($server, '/') . '/' . trim($path, '/');
            }

            return "<img src='$src' style='max-width:{$width}px;max-height:{$height}px' class='img' />";
        })->implode('&nbsp;');
    }
}
